package com.cxl.service.impl;

import com.cxl.entity.Fires;
import com.cxl.es.EsRspository;
import com.cxl.mapper.FiresMapper;
import com.cxl.service.IFiresService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.querydsl.QuerydslUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 崔学磊
 * @since 2022-03-16
 */
@Service
public class FiresServiceImpl extends ServiceImpl<FiresMapper, Fires> implements IFiresService {


    @Autowired
    private FiresMapper firesMapper;

    @Autowired
    private EsRspository esRspository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public Page<Fires> findAll(Fires fires) {
        //组合条件
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNoneBlank(fires.getName())) {
            queryBuilder.must(QueryBuilders.matchQuery("name", fires.getName()));
        }

        //分页
        PageRequest of = PageRequest.of(fires.getPageNum() - 1, fires.getPageSize());

        //构建
        NativeSearchQuery build = new NativeSearchQueryBuilder()
                .withQuery(queryBuilder)
                .withPageable(of)
                .build();

        //封装
        SearchHits<Fires> search = elasticsearchRestTemplate.search(build, Fires.class);

        List<SearchHit<Fires>> searchHits = search.getSearchHits();
        ArrayList<Fires> list = new ArrayList<>();
        for (SearchHit<Fires> searchHit : searchHits) {
            list.add(searchHit.getContent());
        }

        PageImpl<Fires> page = new PageImpl<>(list, of, search.getTotalHits());
        return page;
    }

    @Override
    public void eslist() {
        esRspository.deleteAll();
        List<Fires> slist = firesMapper.findAll();
        esRspository.saveAll(slist);
    }

    @Override
    public Fires getFindOne(Integer id) {
        return firesMapper.getFindOne(id);

    }
}
